<?php
include_once("_common.php");
include_once("$mw_cash[path]/cybercash.lib.php");
include_once("$g4[path]/head.sub.php");

if (!$is_member)
    alert("로그인 후 이용해주세요.");

$mb_id = $member['mb_id'];

if ($membership && !is_array($mi_id))
{
    $row = sql_fetch(" select * from $mw_cash[membership_item_table] where mi_id = '$mi_id' and mi_status = '1' ");
    if (!$row)
        alert("멤버쉽 정보가 없습니다.");

    if ($row[mi_renew]) {
        $sql = " select * from $mw_cash[membership_log_table] ";
        //$sql.= " where mb_id = '$mb_id' and ms_id = '$row[ms_id]' and ml_day = '$row[mi_day]' and ml_edate > '$g4[time_ymdhis]' ";
        $sql.= " where mb_id = '$mb_id' and ms_id = '$row[ms_id]' and ml_edate > '$g4[time_ymdhis]' ";
        $tmp = sql_fetch($sql);
        if (!$tmp)  {
            $tmp = sql_fetch(" select ms_name from $mw_cash[membership_table] where ms_id = '$row[ms_id]' ");
            $ms_name = $tmp[ms_name];

            alert("멤버쉽 [{$ms_name} {$row[mi_day]}일] 상품은 연장만 가능합니다.");
        }
    }

    set_session("cash_membership", "$ms_id@$mi_day");
}

if ($membership && is_array($mi_id))
{
    $list = $mi_id;
    $ac_cash = 0;

    for ($i=0, $m=count($list); $i<$m; $i++) {
        $mi_id = $list[$i];
        $row = sql_fetch(" select * from $mw_cash[membership_item_table] where mi_id = '$mi_id' and mi_status = '1' ");
        if (!$row)
            alert("멤버쉽 정보가 없습니다.");

        if ($row[mi_renew]) {
            $sql = " select * from $mw_cash[membership_log_table] ";
            $sql.= " where mb_id = '$mb_id' and ms_id = '$row[ms_id]' and ml_day = '$row[mi_day]' and ml_edate > '$g4[time_ymdhis]' ";
            $tmp = sql_fetch($sql);
            if (!$tmp)  {
                $tmp = sql_fetch(" select ms_name from $mw_cash[membership_table] where ms_id = '$row[ms_id]' ");
                $ms_name = $tmp[ms_name];

                alert("멤버쉽 [{$ms_name} {$row[mi_day]}일] 상품은 연장만 가능합니다.");
            }
        }

        $cash = $row[mi_cash];
        $discount = 0;

        $sq2 = " select * from $mw_cash[membership_log_table] where mb_id = '$mb_id' and ml_edate > '$g4[time_ymdhis]' and ms_id = '$row[ms_id]' ";
        $ro2 = sql_fetch($sq2);
        if ($ro2) {
            if ($row[mi_cash_extend]) {
                $cash = round($row[mi_cash] * (100-$row[mi_cash_extend])/100);
                $discount = $row[mi_cash_extend];
            }
        }

        // 장기회원 할인
        if ($row[mi_cash_join_day] && $row[mi_cash_join_sale] > $discount && $row[mi_cash_join_day] < ($g4[server_time]-strtotime($member[mb_datetime]))/(60*60*24)) {
            $discount = $row[mi_cash_join_sale];
            $cash = round($row[mi_cash]*(100-$row[mi_cash_join_sale])/100);
        }

        $ac_cash += $cash;
    }
    if (!$i)
        alert("하나 이상 선택해주세요.");

    $ac_cash -= $mw_cash[mb_cash];
    if ($ac_cash <= 0)
        alert("추가 결제할 금액이 없으니 $mw_cash[cf_cash_name](으)로 구매해주세요.");

    set_session("cash_membership", $list);
}
else if ($bo_table and $wr_id) {
    if (!$write)
        alert("컨텐츠 정보가 없습니다.");

    $ac_cash = $write[wr_contents_price];

    set_session("cash_contents", "$bo_table@$wr_id@$no");
}

switch($paytype) {
    case "account": $title = "무통장입금"; break;
    //case "cyber": $title = "무통장입금 (가상계좌)"; break;
    case "card": $title = "신용카드"; break;
    case "bank": $title = "계좌이체"; break;
    case "hp": $title = "핸드폰 결제"; break;
    case "paypal": $title = "페이팔 결제"; break;
    default:
	alert_close("결제방법이 잘못되었습니다.");
}

$is_paypal = false;
if ($mw_cash[cf_paypal] && $paytype == 'paypal') {
    $is_paypal = true;
}

if ($is_paypal) {
    $ac_payment = $ac_cash * $mw_cash[cf_paypal_dollar];
} else {
    $ac_payment = mw_cash_to_payment($ac_cash, $mw_cash[cf_tax]);

    if ($paytype == "account")
        $charge_min = $mw_cash[cf_charge_min];
    else
        $charge_min = $mw_cash[cf_card_min];

    if ($mw_cash[cf_tax])
        $charge_min *= 1.1;

    if ($charge_min > $ac_payment)
        alert(number_format($charge_min)."원 (부가세포함) 이상 충전하실 수 있습니다.");	
}

switch ($paytype) {
    case "account": // 무통장입금
        sql_query("alter table $mw_cash[account_table] add ac_ip varchar(20) not null after ac_hp", false);
        sql_query("alter table $mw_cash[account_table] add ac_agent varchar(255) not null after ac_ip", false);
	$sql = "insert into $mw_cash[account_table]
		   set mb_id = '$mb_id',
		       ac_name = '$ac_name',
		       ac_hp = '$ac_hp',
                       ac_ip = '$_SERVER[REMOTE_ADDR]',
                       ac_agent = '$_SERVER[HTTP_USER_AGENT]',
		       ac_payment = '$ac_payment',
		       ac_datetime = '$g4[time_ymdhis]',
		       ac_memo = '$ac_memo',
		       ac_status = '입금신청',
		       ac_tax = '$mw_cash[cf_tax]'";
	sql_query($sql);
	if ($mw_cash[cf_admin_sms]) {
	    $icode_id = $mw_cash[cf_icode_id];
	    $icode_pw = $mw_cash[cf_icode_pw];
	    $msg = "[$mw_cash[cf_cash_name]]\n무통장 입금신청\n".number_format($ac_payment)."원\n$ac_name";
            $hps = explode("\n", $mw_cash[cf_admin_sms_return]);
	    mw_cash_sms_send($hps, $mw_cash[cf_sms_return], $msg);
	}
        if ($mw_cash[cf_sms]) {
            $mb = get_member($mb_id, "mb_name, mb_nick, mb_hp");
            $msg = $mw_cash[cf_sms_account];
            $msg = str_replace("{계좌}", str_replace(" ", "\n", $mw_cash[cf_account_num]), $msg);
            $msg = str_replace("{캐쉬}", $mw_cash[cf_cash_name], $msg);
            $msg = str_replace("{충전수}", mw_payment_to_cash($ac_payment, $mw_cash[cf_tax]).$mw_cash[cf_cash_unit], $msg);
            $msg = str_replace("{이름}", $mb[mb_name], $msg);
            $msg = str_replace("{별명}", $mb[mb_nick], $msg);
            $msg = str_replace("{금액}", number_format($ac_payment), $msg);
            if (mw_cash_is_hp($ac_hp))
                mw_cash_sms_send($ac_hp, $mw_cash[cf_sms_return], $msg);
        }
	?>
	<script type="text/javascript">
	window.onload = function () {
	    alert("입금신청이 완료되었습니다.");
	    opener.location.href = "account-list.php";
	    //opener.location.reload();
	    self.close();
	}
	</script>
	<?
	break;

    case "paypal": // 페이팔
	set_session("pid", $pid);
	//$mb_id = $member[mb_id];
	$cl_cash = $ac_cash;
	$cl_content = "[충전] $title(".number_format($ac_payment)."$)→{$mw_cash[cf_cash_name]}(".number_format($cl_cash)."{$mw_cash[cf_cash_unit]})";
	$cl_payment = $ac_payment;
	$cl_paytype = mw_get_paytype($paytype);
	$cl_paylog = "";
	$cl_admin_memo = "";
	$cl_status = "";
	$cl_id = mw_cash_charge($mb_id, $cl_cash, $cl_content, $cl_payment, $cl_paytype, $cl_paylog, $cl_admin_memo, $cl_status);
	goto_url("cash-charge-card.php?cl_id=$cl_id&bo_table=$bo_table");
	break;

    default:
        set_session("pid", $pid);
        //$mb_id = $member[mb_id];
        $cl_cash = $ac_cash;
        $cl_content = "[충전] $title(".number_format($ac_payment)."원)→{$mw_cash[cf_cash_name]}(".number_format($cl_cash)."{$mw_cash[cf_cash_unit]})";
        $cl_payment = $ac_payment;
        $cl_paytype = mw_get_paytype($paytype);
        $cl_paylog = "";
        $cl_admin_memo = "";
        $cl_status = "";
        $cl_id = mw_cash_charge($mb_id, $cl_cash, $cl_content, $cl_payment, $cl_paytype, $cl_paylog, $cl_admin_memo, $cl_status);
        goto_url("cash-charge-card.php?cl_id=$cl_id&bo_table=$bo_table");
        break;
}

include_once("$g4[path]/tail.sub.php");
